
package com.bbh.plugin.single.privilege.demo.controller;

import com.bbh.plugin.single.privilege.core.entity.App;
import com.bbh.plugin.single.privilege.core.entity.Resource;
import com.bbh.plugin.single.privilege.core.enums.BaseEnum;
import com.bbh.plugin.single.privilege.core.service.AppService;
import com.bbh.plugin.single.privilege.core.service.ResourceService;
import com.bbh.plugin.single.privilege.core.vo.tree.ResourceVo;
import com.bbh.plugin.single.privilege.core.vo.tree.TreeTableVo;
import com.bbh.plugin.single.privilege.core.vo.tree.ZTreeNoneAjaxVo;
import com.bbh.common.domain.Condition;
import com.bbh.common.domain.Message;
import com.bbh.common.domain.StatusType;
import com.bbh.common.utils.IdUtils64;
import com.bbh.common.utils.mapper.JsonMapper;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.util.Assert;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * Controller - 菜单
 *
 * @author KCSHOP Team
 * @version 3.0
 */
@Controller
@RequestMapping("/resource")
public class ResourceController extends BasicController {
    @Autowired
    private ResourceService resourceService;
    @Autowired
    private AppService appService;

    /**
     * 跳转资源列表页面
     *
     * @author bestgwd
     */
    @RequestMapping(value = VIEW_FILED + "/index", method = RequestMethod.GET)
    public String index(ModelMap model) {
        return "single/resource/index";
    }

    /**
     * 跳转资源增加页面
     *
     * @param
     * @return
     */
    @RequestMapping(value = INSERT_FILED + "/toAdd", method = RequestMethod.GET)
    public String toAddResource(ModelMap model, String parentId) {
        Assert.hasText(parentId);
        Resource parent = resourceService.selectByPrimaryKey(parentId);
        Assert.notNull(parent);
        App app = new App();
        if (!"BUSINESS".equals(parent.getAppCode())) {
            app = appService.findByAppNameCode(parent.getAppCode());
        }
        model.put("parent", parent);
        model.put("app", app);
        model.put(OPERATE_TYPE, "add");
        return "single/resource/edit";
    }

    /**
     * 提交资源
     *
     * @param resource
     * @return
     */
    @RequestMapping(value = INSERT_FILED + "/insert", method = RequestMethod.POST)
    public
    @ResponseBody
    Message addResource(Resource resource) {
        Assert.hasText(resource.getParentId());
        Date now = new Date();
        Resource parent = resourceService.selectByPrimaryKey(resource.getParentId());
        resource.setId(IdUtils64.getInstance().getStringId());
        resource.setCreateBy(getPrincipal().getLoginName());
        resource.setCreateTime(now);
        resource.setModifyBy(getPrincipal().getLoginName());
        resource.setModifyTime(now);
        resource.setDataStatus(BaseEnum.DATA_STATUS.NORMAL.getKey());
        //如果是业务系统资源管理的第一级下级,需要选择对应的业务系统
        if ("BUSINESS".equals(parent.getAppCode())) {
            Assert.hasText(resource.getAppCode());
        } else {
            resource.setAppCode(parent.getAppCode());
        }
        resourceService.insert(resource);
        return new Message(StatusType.SUCCESS.getKey(), "保存成功");
    }

    /**
     * 删除菜单
     *
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = DELETE_FILED + "/del", method = RequestMethod.POST)
    public Message delResource(String id) {
        Resource resource = resourceService.selectByPrimaryKey(id);
        if ("-1".equals(resource.getParentId())) {
            return new Message(StatusType.ERROR.getKey(), "系统内置资源,不可删除");
        }
        Condition condition = new Condition();
        condition.put("parentId", id);
        condition.put(DATA_STATUS, BaseEnum.DATA_STATUS.NORMAL.getKey());
        List<ResourceVo> resourceVoList = resourceService.findChildren(condition);
        if (CollectionUtils.isNotEmpty(resourceVoList)) {
            return new Message(StatusType.WARN.getKey(), "请先删除下级资源");
        } else {
            resource.setDataStatus(BaseEnum.DATA_STATUS.DELETE.getKey());//设置不可用
            resource.setModifyBy(getPrincipal().getLoginName());
            resource.setModifyTime(new Date());
            resourceService.updateByPrimaryKeySelective(resource);
        }
        return new Message(StatusType.SUCCESS.getKey(), "删除成功");
    }

    /**
     * 跳转更新页面
     *
     * @param model
     * @return
     */
    @RequestMapping(value = UPDATE_FILED + "/toEdit", method = RequestMethod.GET)
    public String toUpdateResource(ModelMap model, String id) {
        Assert.hasText(id);
        Resource resource = resourceService.selectByPrimaryKey(id);
        Assert.notNull(resource);
        Resource parent = resourceService.selectByPrimaryKey(resource.getParentId());
        Assert.notNull(parent);
        App app = appService.findByAppNameCode(resource.getAppCode());
        model.put("app", app);
        model.put("resource", resource);
        model.put("parent", parent);
        model.put(OPERATE_TYPE, "edit");
        return "single/resource/edit";
    }

    /**
     * 更新菜单
     *
     * @param resource
     * @return
     */
    @RequestMapping(value = UPDATE_FILED + "/update", method = RequestMethod.POST)
    public
    @ResponseBody
    Message updateResource(Resource resource) {
        Assert.hasText(resource.getId(), "参数错误");
        Resource updateResource = resourceService.selectByPrimaryKey(resource.getId());
        Assert.notNull(updateResource);
        if (updateResource != null) {
            updateResource.setName(resource.getName());
            if (!resource.getAppCode().equals(updateResource.getAppCode())) {
                updateResource.setAppCode(resource.getAppCode());//最好下级所有的code都要修改
            }
            updateResource.setSort(resource.getSort());
            updateResource.setTarget(resource.getTarget());
            updateResource.setIcon(resource.getIcon());
            updateResource.setPermissionKey(resource.getPermissionKey());
            updateResource.setPermissionValue(resource.getPermissionValue());
            updateResource.setUrl(resource.getUrl());
            updateResource.setDescription(resource.getDescription());
            updateResource.setIsEnabled(resource.getIsEnabled());
            updateResource.setModifyBy(getPrincipal().getLoginName());
            updateResource.setType(resource.getType());
            updateResource.setModifyTime(new Date());
            resourceService.updateByPrimaryKeySelective(updateResource);
        }
        return new Message(StatusType.SUCCESS.getKey(), "保存成功");
    }

    /**
     * 获取菜单列表
     *
     * @param request
     * @param model
     * @param id
     * @return
     * @throws ServletRequestBindingException
     */
    @RequestMapping(VIEW_FILED + "/list")
    @ResponseBody
    public TreeTableVo list(HttpServletRequest request, Model model, String id) throws ServletRequestBindingException {
        Condition condition = new Condition();
        condition.put(DATA_STATUS, BaseEnum.DATA_STATUS.NORMAL.getKey());
        condition.put("parentId", null == id ? -1 : id);
        List<ResourceVo> list = resourceService.findChildren(condition);
        TreeTableVo treeTableVo = new TreeTableVo();
        treeTableVo.setRows(list);
        return treeTableVo;
    }

    /**
     * 更新排序
     *
     * @param id
     * @param sort
     * @return
     */
    @ResponseBody
    @RequestMapping(value = UPDATE_FILED + "/updateSort", method = RequestMethod.POST)
    public Message updateResourceSort(@RequestParam(value = "id") String id, @RequestParam(value = "sort") Long sort) {
        Resource resource = new Resource();
        resource.setId(id);
        resource.setSort(sort);
        resource.setModifyTime(new Date());
        resourceService.updateByPrimaryKeySelective(resource);
        Message message = new Message(StatusType.SUCCESS.getKey(), "更新成功");
        return message;
    }

    /**
     * 获取图标资源
     *
     * @return
     */
    @RequestMapping(value = VIEW_FILED + "/icon", method = RequestMethod.POST)
    public String icon() {
        return "resource/icon";
    }


    @ResponseBody
    @RequestMapping(VIEW_FILED + "/treeList")
    public String treeList(String callback, String name, String roleId) {
        Condition condition = new Condition();
        if (StringUtils.isNotBlank(name)) {
            condition.put("resourceName", name);
        }
        if (StringUtils.isNotBlank(roleId)) {
            condition.put("roleId", roleId);
        }
        condition.put("dataStatus", BaseEnum.DATA_STATUS.NORMAL.getKey());
        List<ZTreeNoneAjaxVo> list = resourceService.selectTreeResource(condition);
        return JsonMapper.nonEmptyMapper().toJsonP(callback, list);
    }

}